﻿#include "dwgrect.h"
#include <QtMath>
Dwgrect::Dwgrect(QObject *parent)
    : DwgObject{parent}
{}

void Dwgrect::SetData(QPointF pt1, QPointF pt2)
{
    x=pt1.x();
    y=pt1.y();
    w=(pt2.x()-pt1.x())?(pt2.x()-pt1.x()):(pt1.x()-pt2.x());
    h=(pt2.y()-pt1.y())?(pt2.y()-pt1.y()):(pt1.y()-pt2.y());
}

void Dwgrect::Draw(QPainter *painter)
{
    //=========抑制线宽变化========//
    QPen pen;
    pen.setCosmetic(true);       // 允许线宽缩放
    pen.setWidth(1);             // 使用逻辑线宽
    painter->setPen(pen);
    //==========选择+删除=========//
    if(mDeleteed) return;
    if(mSelected)
    {
        painter->setPen(Qt::red);
    }

    painter->drawRect(x,y,w,h);
    painter->setPen(Qt::black);
}

//==选择+删除==//
void Dwgrect::Select(QPointF pt)
{
    // 矩形的四个边
    QLineF topEdge(QPointF(x, y), QPointF(x + w, y));      // 上边
    QLineF bottomEdge(QPointF(x, y + h), QPointF(x + w, y + h)); // 下边
    QLineF leftEdge(QPointF(x, y), QPointF(x, y + h));      // 左边
    QLineF rightEdge(QPointF(x + w, y), QPointF(x + w, y + h)); // 右边

    // 计算点到四条边的距离
    auto distanceToLine = [](const QPointF& pt, const QLineF& line) {
        qreal A = pt.y() - line.p1().y();
        qreal B = line.p2().x() - line.p1().x();
        qreal C = line.p1().x() - pt.x();
        qreal D = line.p2().y() - line.p1().y();
        // 手动计算平方和的平方根
        return std::abs(A * B + C * D) / std::sqrt(B*B + D*D);
    };

    qreal distTop = distanceToLine(pt, topEdge);
    qreal distBottom = distanceToLine(pt, bottomEdge);
    qreal distLeft = distanceToLine(pt, leftEdge);
    qreal distRight = distanceToLine(pt, rightEdge);

    // 如果点靠近任意一条边（距离 < 3 像素），则选中
    if (distTop < 3 || distBottom < 3 || distLeft < 3 || distRight < 3) {
        mSelected = true;
    }
}
